package com.wh.util.encode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class CVTFileEncoding {
	static void cvt(File dirOrFile, String suffix, String from, String to) throws IOException {
		if (dirOrFile.isFile()) {
			String fp = dirOrFile.getAbsolutePath();
			if (!fp.endsWith(suffix)) return;
			if (fp.contains(".svn")) return;
			System.out.println("转换文件：" + fp);
			StringBuffer document = new StringBuffer();
			InputStream fin = new FileInputStream(dirOrFile);
			BufferedReader reader = new BufferedReader(new InputStreamReader(fin, from));
			char[] chars = new char[100];
			int reads = 0;
			while ((reads = reader.read(chars)) != -1) {
				document.append(chars, 0, reads);
			}
			reader.close();
			fin.close();
			// System.out.println(document.toString());
			//
			OutputStream fos = new FileOutputStream(dirOrFile);
			Writer w = new OutputStreamWriter(fos, to);
			w.write(document.toString());
			w.flush();
			w.close();
			fos.close();
			return;
		} else {
			File[] fs = dirOrFile.listFiles();
			if (fs != null) for (File file : fs) {
				cvt(file, suffix, from, to);
			}
		}
	}

	public static void main(String[] args) {
		String f = "src/main/java/com/wh/minihelp/flower/domain";
		// System.out.println(f);
		try {
			cvt(new File(f), ".java", "GBK", "UTF-8");
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}
